const db = require('../../db/index');
const {PublisherModel} = require('../../model/Publisher/Pubilsher');
const {UserModel} = require('../../model/UserSchema/User')
const {CompanyModel} = require('../../model/CompanySchema/Company')


// 检测userid是否有效
exports.isValid_userId = function (userId) {
    return new Promise((resolve, reject) => {
        UserModel.count({_id:userId},(error, result) => {
            if (error) return reject(error)
            if(result>0) return resolve({boolean:true})
            return resolve({boolean:false})
        })
    })
}
// 检测companyId是否有效
exports.isValid_companyId = function (companyId) {
    return new Promise((resolve, reject) => {
        CompanyModel.count({_id:companyId},(error, result) => {
            if (error) return reject(error)
            if(result>0) return resolve({boolean:true})
            return resolve({boolean:false})
        })
    })
}
// 检测是否重复注册成为发布者（一个发布者可以加盟多个公司，不可加盟同一个公司两次）
exports.isRepeatRegister = function (UserId,CompanyId) {
    return new Promise((resolve, reject) => {
        PublisherModel.count({UserId,CompanyId},(error, result) => {
            console.log(result)
            if (error) return reject(error)
            if(result>0) return resolve({boolean:true})
            return resolve({boolean:false})
        })
    })
}

// 添加发布者信息
exports.Add = function (arg) {
    return new Promise((resolve, reject) => {
        const publisherModel = new PublisherModel({
            UserId: arg.UserId,
            CompanyId: arg.CompanyId,
            joinTime: new Date().getTime()
        })
        publisherModel.save((error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
};


/* 查询用户信息(只允许单条件查询)
        用户id,手机号,
* */
exports.Sel_singleArg = function (arg) {
    return new Promise((resolve, reject) => {
        UserModel.find({...arg}, (error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
};

// 查询文档中的对象/数组的属性
/*
*   @key           需要匹配的键名
*   @value         需要匹配的值
*   @filterOptions 需要过滤的属性
* */
exports.Sel_quoteType = function (key, value, filterOptions) {
    return new Promise((resolve, reject) => {
        console.log({[key]: value})
        UserModel.find({[key]: value}, filterOptions, (error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
}

// 修改信息
exports.Upd = function (_id, UpdateObject) {
    return new Promise((resolve, reject) => {
        UserModel.findByIdAndUpdate({_id}, UpdateObject, (error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
}
